package com.supermap.map;
import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.telecom.Call;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ZoomControls;

import com.supermap.data.Color;
import com.supermap.data.Datasource;
import com.supermap.data.DatasourceConnectionInfo;
import com.supermap.data.EngineType;
import com.supermap.data.Environment;
import com.supermap.data.FillGradientMode;
import com.supermap.data.GeoLine;
import com.supermap.data.GeoPoint;
import com.supermap.data.GeoRegion;
import com.supermap.data.GeoStyle;
import com.supermap.data.Point2D;
import com.supermap.data.Point2Ds;
import com.supermap.data.Rectangle2D;
import com.supermap.data.Size2D;
import com.supermap.data.Workspace;
import com.supermap.data.WorkspaceConnectionInfo;
import com.supermap.data.WorkspaceType;
import com.supermap.mapping.CallOut;
import com.supermap.mapping.MapControl;
import com.supermap.mapping.MapView;
import com.supermap.mapping.TrackingLayer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity extends Activity  {

    private MapControl m_mapcontrol = null;


    /**
     * 需要申请的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestPermissions();

        String rootPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();

        //设置一些系统需要用到的路径
        Environment.setLicensePath(rootPath + "/SuperMap/license/");
        Environment.setTemporaryPath(rootPath + "/SuperMap/temp/");
        Environment.setWebCacheDirectory(rootPath + "/SuperMap/WebCatch");

        //组件功能必须在Environment初始化之后才能调用
        Environment.initialization(this);


        File file = new File(rootPath + "/SuperMap/license/SuperMap iMobile Trial-20210115.slm");
        if(file.exists()){
            System.out.println("true");
        }else{
            System.out.println("false");
        }

        //如果机器中默认不包括需要显示的字体，可以把相关字体文件放在参数所代表的路径中。
        //例如，如果需要显示阿拉伯文字（若机器中原先不包括相关字体文件），可以把需要的字体文件放在参数所代表的路径中。
        Environment.setFontsPath(rootPath + "/SuperMap/fonts/");
        setContentView(R.layout.activity_main);

        //打开工作空间
        Workspace m_workspace = new Workspace();
        WorkspaceConnectionInfo info = new WorkspaceConnectionInfo();
       // info.setServer(rootPath + "/SampleData/GeometryInfo/World.smwu");

        info.setServer(rootPath + "/SampleData/tujidata/tuijtt2.smwu");
        info.setType(WorkspaceType.SMWU);
        m_workspace.open(info);




        //将地图显示控件和工作空间关联
        MapView m_mapView = findViewById(R.id.Map_view);
        m_mapcontrol = m_mapView.getMapControl();
        m_mapcontrol.getMap().setWorkspace(m_workspace);

        //打开工作空间内地图
        openWorkspaceMap(m_workspace);


        //以数据源的方式打开MVT数据
        DatasourceConnectionInfo dsInfo = new DatasourceConnectionInfo();
        dsInfo.setServer(rootPath + "/SampleData/Country_R/Country_R/styles/style.json");
        dsInfo.setEngineType(EngineType.MVTCache);
        dsInfo.setAlias("MVT");
        Datasource ds = m_workspace.getDatasources().open(dsInfo);
        if (ds == null) {
            return;
        }
        Log.e("MainActivity", "left: " + ds.getDatasets().get(0).getBounds().getLeft() + ", right: " + ds.getDatasets().get(0).getBounds().getRight());
        //地图显示范围可在iDesktop中，通过地图属性查看
        m_mapcontrol.getMap().getLayers().add(ds.getDatasets().get(0), true);
        m_mapcontrol.getMap().setScale(0.0001);



        //实例化一个跟踪图层
        TrackingLayer trackingLayer = m_mapcontrol.getMap().getTrackingLayer();
        //添加点对象
        addGeoPoint(trackingLayer);
        //添加面对象
        addGeoRegion(trackingLayer);
        //添加线对象
        addLine(trackingLayer);


        ZoomControls m_zoom = findViewById(R.id.zoomControls1);
        m_zoom.setIsZoomInEnabled(true);
        m_zoom.setIsZoomOutEnabled(true);

        //放大按钮
        m_zoom.setOnZoomInClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_mapcontrol.getMap().zoom(2);
                m_mapcontrol.getMap().refresh();
            }
        });

        //缩小按钮
        m_zoom.setOnZoomOutClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_mapcontrol.getMap().zoom(0.5);
                m_mapcontrol.getMap().refresh();
            }
        });
        m_mapcontrol.getMap().setCenter(new Point2D(116.23,41.23));
        m_mapcontrol.getMap().setScale(0.0001);
        m_mapcontrol.getMap().refresh();
    }

    private void openWorkspaceMap(Workspace m_workspace) {
        //        //打开工作空间中的第二幅地图
        String mapName = m_workspace.getMaps().get(0);
        m_mapcontrol.getMap().open(mapName);
    }

    /**
     * 添加点对象
     * @param trackingLayer
     */
    private void addGeoPoint(TrackingLayer trackingLayer) {
        // 实例化一个风格对象，并进行相应设置
        GeoStyle geoStyle_P = new GeoStyle();
        geoStyle_P.setMarkerAngle(14.0);
        /*设置点状符号的大小，单位为毫米，精确到0.1毫米*/
        geoStyle_P.setMarkerSize(new Size2D(3, 3));
        //设置点的符号，每个点符号对应一个值
        geoStyle_P.setMarkerSymbolID(2);
        //设置点颜色，只有自带的几个点符号可以改颜色，自定义的图像应该不能改
        geoStyle_P.setPointColor(new Color(255,0,0));
        //实例化一个点几何对象
        GeoPoint geoPoint = new GeoPoint(116.23, 41.23);
        geoPoint.setStyle(geoStyle_P);
        //把点添加到跟踪图层
        trackingLayer.add(geoPoint, "point");
    }

    /**
     * 添加几何面对象
     * @param trackingLayer
     */
    private void addGeoRegion(TrackingLayer trackingLayer) {
        GeoStyle geoStyle_R = new GeoStyle();
        geoStyle_R.setFillBackColor(new Color(0,255,0));
        geoStyle_R.setFillForeColor(new Color(255,0,0));
        geoStyle_R.setFillBackOpaque(true);
        geoStyle_R.setFillOpaqueRate(50);
        geoStyle_R.setFillGradientAngle(30.0);                     //OpenGL不支持颜色渐变
        geoStyle_R.setFillGradientMode(FillGradientMode.LINEAR);   //OpenGL不支持颜色渐变
        Point2Ds point2Ds_R = new Point2Ds();
        Point2D[] point2DArray_R = {new Point2D(116.23, 41.23), new Point2D(116.23, 42.23),
                new Point2D(117.23, 41.23), new Point2D(117.23, 42.23)};
        point2Ds_R.addRange(point2DArray_R);
        GeoRegion geoRegion = new GeoRegion(point2Ds_R);
        geoRegion.setStyle(geoStyle_R);

        trackingLayer.add(geoRegion,"Region");
    }

    /**
     * 添加线对象
     * @param trackingLayer
     */
    private void addLine(TrackingLayer trackingLayer) {
        //添加线对象
        GeoStyle geoStyle_l = new GeoStyle();
        geoStyle_l.setLineColor(new Color(255,255,9));
        geoStyle_l.setLineWidth(2);
        GeoLine geoLine = new GeoLine(new Point2Ds(new Point2D[]{new Point2D(108, 35), new Point2D(116.23, 42.23)}));
        geoLine.setStyle(geoStyle_l);
        trackingLayer.add(geoLine,"Line");
    }

    /**
     * 申请动态权限
     */
    private void requestPermissions() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        if (!checkPermissions(needPermissions)) {
            EasyPermissions.requestPermissions(
                    this,
                    "为了应用的正常使用，请允许以下权限。",
                    0,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.CHANGE_WIFI_STATE);
            //没有授权，编写申请权限代码
        } else {
            //已经授权，执行操作代码
        }
    }


    /**
     * 检测权限
     * return true:已经获取权限
     * return false: 未获取权限，主动请求权限
     */

    public boolean checkPermissions(String[] permissions) {
        return EasyPermissions.hasPermissions(this, permissions);
    }




}